Skip to content

fix(service-ai): estimate non-zero token usage in MemoryLLMAdapter - #2000

Merged
os-zhuang merged 1 commit into
mainfrom
fix/memory-adapter-token-usage
Jun 17, 2026
Merged

os-zhuang merged 1 commit into
mainfrom
fix/memory-adapter-token-usage

Conversation

@os-zhuang

Copy link
Copy Markdown
Contributor

Problem

MemoryLLMAdapter is the money-free stand-in for a real LLM in dev, CI, and local E2E. But it hardcoded usage: { promptTokens: 0, completionTokens: 0, totalTokens: 0 } on every return path (chat, complete, streamChat finish, generateObject, tool-call and error branches).

Consequence: any feature that meters tokens — cloud's AI quota guardrail, free-tier lifetime caps, paid monthly hard cap, usage dashboards, cost self-stop — could not be exercised end-to-end without a paid provider key. You literally had to spend real API money to test a cost-control feature.

Fix

Estimate usage crudely from the prompt messages + echoed output (~4 chars/token, the standard ballpark) and return it on all paths via two small helpers (estimateTokens / estimateUsage).

This is intentionally not provider-accurate — it only needs to be non-zero, additive (total = prompt + completion), and grow with input size, so usage-driven behaviour is testable money-free.

Test

Adds a unit test asserting the new usage is non-zero, additive, and monotonic in input size. Full file: 103/103 pass.

Verification

Confirmed live in local E2E: assistant ai_messages rows now meter ~5000 tokens each (previously 0), which lets the cloud token guardrail actually accumulate toward its caps using the echo adapter.

🤖 Generated with Claude Code

The in-memory adapter stands in for a real LLM in dev/CI/local-E2E, but
returned a flat `usage: {0,0,0}` on every path. That made every
token-metering feature — quota guardrails, lifetime caps, usage
dashboards, cost stops — impossible to exercise without a paid provider
key, i.e. without spending real money.

Estimate usage crudely (~4 chars/token, the standard ballpark) from the
prompt messages and echoed output across chat/complete/streamChat/
generateObject. Intentionally NOT provider-accurate — it exists so
usage-driven behaviour is testable money-free, not to bill anyone.

Adds a unit test asserting non-zero, additive (total = prompt+completion),
monotonic-in-input-size usage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@vercel

vercel Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
spec Ready Ready Preview, Comment Jun 17, 2026 3:38am

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): packages/services.

5 hand-written doc(s) reference the affected code and may need an implementation-accuracy re-verification:

  • content/docs/guides/packages.mdx (via packages/services)
  • content/docs/guides/runtime-services/audit-service.mdx (via packages/services)
  • content/docs/guides/runtime-services/index.mdx (via packages/services)
  • content/docs/guides/runtime-services/settings-service.mdx (via packages/services)
  • content/docs/protocol/objectos/i18n-standard.mdx (via packages/services)

Advisory only. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs origin/main → pass the list as args.docs.

@os-zhuang
os-zhuang merged commit 3029236 into main Jun 17, 2026
13 checks passed
@os-zhuang
os-zhuang deleted the fix/memory-adapter-token-usage branch June 17, 2026 05:46
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ck-ai#36757)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8JpuMUc83TvQP7B2uT2pUz5)_

Part of objectstack-ai#36740 — this PR lands card items 1–3 (the script, the page
template, the runbook). Item 4, the one skill line in the triage lane
file, is governed text, so it follows as its own PR carrying the closing
keyword once this one merges; keeping it out keeps this diff out of Tier
H.

Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户无感:专题看板的生成脚本、页面模板和刷新手册从分诊会话的临时目录搬进仓库。
- 属于车队工具:分诊换人或换号后,新座位照手册就能继续每 3 小时刷新看板。
- 只读 GitHub、不写任何东西;出错最多是看板某次数字不对,下次刷新即恢复,可直接撤回。
- 无

## What changes

- `scripts/pm/topic-board.mjs` (new): a Node port of the reference
`build.py` from the card. `--repo=objectstack|cloud --out=DIR` writes
`epics{,_cloud}.json` and `areas{,_cloud}.json`; `--self-test` runs
offline. Read-only: every read goes through `gh-pages.mjs` (`gh api`,
the shared `scripts/pm` read path); a failed read exits 3 and writes
nothing. The retired `lanes` output (and the seat roster that fed it) is
not ported.
- `scripts/pm/topic-board/page.html` (new): the card's page template, as
attached on the card, unchanged (no path needed fixing).
- `scripts/pm/topic-board/README.md` (new): the 3-hourly runbook — build
both repos, upload the four JSON files one per call, repoint the four
dataset docs with `if_version`, delete superseded blobs; artifact
ownership across accounts; reading a stale row; no artifact URL in the
repo.
- `package.json`: the self-test is chained onto the existing
`check:pm-board-snapshot` script, so CI runs it with no workflow edit.

## Why

The board builder lived only in triage#1's session scratchpad and dies
with it; the maintainer ordered it into the repo so any triage seat, on
any account, can keep refreshing the board.

## Tests

`node scripts/pm/topic-board.mjs --self-test` — 38 cases, all pass,
offline. It pins: topic detection (`pm:epic`, `[Epic …]`, `[专题 …]`,
`专题:`, `tracking` with open subs; a closed-out tracking card and a
`pm:seat` card are not topics); parent choice (direct holder beats a
larger containing topic; a cycle keeps one link); rollup (a parent's
numbers include its descendant topics' cards, topic cards never count as
members, closed sub-issues count in total/closed); prose-linked
"unlinked" members (`objectstack-ai#2000` and `#200号` do not match `objectstack-ai#200`); topic
cards left out of the area table with `topic_skipped`; the 「(未定 area)」
row; the read path (pull requests dropped, request count, a failed
sub-issues read fails the whole read).

A one-off mutation (direct-holder rule replaced by "any containing
topic") turned three cases red, then was restored before the commit (the
original line read back).

## Acceptance notes

- Pacing is at or below the reference's: one paginated open-issues list,
one sub-issues read per topic, and one per sub-issue whose
`sub_issues_summary.total` is above zero (or absent). The reference read
every sub-issue's sub-issues unconditionally; the members found are the
same.
- Area rows: every area of the repo's list gets a row in list order,
zero or not, so the page shows every area group; others follow by open
count, then 「(未定 area)」. The reference emitted only areas with cards,
sorted by count; the page sorts groups by its own order, so only zero
groups are new. `topic` is 0 by construction (as in the reference) and
kept for the page's shape.
- Faithful to the reference, kept as is: a card detected as a topic by
title alone (no `pm:epic` / `tracking` label) is not in the area table's
skip list, so it counts there when it sits in no other topic.
- Live-count check (done-when 1) is not measured here: this container's
`gh` is limited to search. NOT MEASURED: live read, reason: no
non-search `gh api` in this container. It is the triage seat's reading,
on its next refresh, from a checkout of this branch:

  ```sh
  node scripts/pm/topic-board.mjs --repo=objectstack --out=DIR
  node scripts/pm/topic-board.mjs --repo=cloud --out=DIR
  ```

Then compare `DIR/epics.json`, `DIR/areas.json`, `DIR/epics_cloud.json`
and `DIR/areas_cloud.json` with the datasets of triage#1's last
published refresh: per topic `open`/`total`/`closed`/`unlinked`, per
area `open`/`p1`, and `topic_skipped`. They should match within the
cards that changed between the two builds; the only expected structural
difference is the new zero rows for areas with no open cards. The stdout
summary line also prints the GET request count of each run.

## Verification

Read first: `buildBoard` in `scripts/pm/topic-board.mjs` (the parent
choice and the cycle guard), then `readBoard` (the read count and
failure path).

Two-minute check: `node scripts/pm/topic-board.mjs --self-test` →
`topic-board self-test: all passed`.

The page was rendered in Chromium from the script's own output on a
fixture (stub `dash`/`d3`): no page errors, both tabs draw the area
groups, the topic tree (child under parent) and the 「专题以外」 rows.

<details><summary>Local gates at b85141c (dispatch-gates --commands: 42
families)</summary>

`node scripts/pm/dispatch-gates.mjs --ran` → `42 derived famil(ies)
accounted for — 38 run, 4 NOT-MEASURED`. All 38 run exit 0, including
`pnpm check:pm-board-snapshot` (now carrying this self-test), `node
scripts/check-self-test-wired.mjs` and `pnpm check:pm-dispatch-gates`
(fast tier 459 s, exit 0).

NOT MEASURED (exit 3, PREREQUISITE NOT MET — they read built `dist/`,
and this diff touches no package): `check:dts-closure`,
`check:dual-build-cjs-loads`, `check:lean-entry-closure`,
`check:sourcemap-no-sources-content`. CI builds and runs them.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01JQwxba6Siz8egCv4AAnqtU

<!-- signed: repo:objectstack#1 · os-warren ·
session_01JQwxba6Siz8egCv4AAnqtU -->

Co-authored-by: Claude <noreply@anthropic.com>

This branch was successfully deployed

1 active deployment
Preview — 2b2d851b Deployed Jun 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant